﻿using System;
using System.ComponentModel;
using System.Linq.Expressions;
using System.Reflection;

namespace Integrity
{
  internal static class ObservableHelper
  {
    public static PropertyChangedEventArgs CreateArgs<T, U>(Expression<Func<T, U>> propertyExpression)
    {
      return new PropertyChangedEventArgs(GetPropertyName(propertyExpression));
    }

    public static string GetPropertyName<T, U>(Expression<Func<T, U>> propertyExpression)
    {
      var lambda = propertyExpression as LambdaExpression;
      MemberExpression memberExpression;
      if (lambda.Body is UnaryExpression)
      {
        var unaryExpression = lambda.Body as UnaryExpression;
        memberExpression = unaryExpression.Operand as MemberExpression;
      }
      else
      {
        memberExpression = lambda.Body as MemberExpression;
      }

      var propertyInfo = memberExpression.Member as PropertyInfo;

      return propertyInfo.Name;
    }    
  }
}